using System.Collections;
using UnityEngine;

public class GunShoot : MonoBehaviour
{
    private AudioSource audio;
    public AudioClip ShotSound;
    public float WeaponAttackSpeed; // 武器射速
    public float WeaponMoveSpeed;//武器带来的移速
    public GameObject bulletPrefab; // 子弹预制体
    public Transform muzzlePos; // 枪口位置
    public Vector2 mousePos; // 鼠标位置
    public Vector2 direction; // 鼠标方向
    private float timer; // 计时器
    private Animator animator;
    private Player player; // 引用Player脚本

    void Start()
    {
        audio = GetComponent<AudioSource>();
        muzzlePos = transform.Find("Muzzle");
        player = GetComponentInParent<Player>();
    }

    void Update()
    {
        mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition); // 获得鼠标的世界坐标
        Shoot();
        //Debug.Log(timer);
    }

    // ReSharper disable Unity.PerformanceAnalysis
    void Shoot()
    {
        direction = (mousePos - new Vector2(transform.position.x, transform.position.y)).normalized;
        transform.right = direction; // 枪械指向鼠标位置

        // 射击时间
        if (timer != 0)
        {
            timer -= Time.deltaTime;
            if (timer <= 0)
            {
                timer = 0;
            }
        }
        // 开火
        if (Input.GetButton("Fire1"))
        {
            if (timer == 0)
            {
                Fire(); 
                timer = 1f / ((player.stats.attackSpeed + player.stats.tempAttackSpeed) *WeaponAttackSpeed*player.stats.attackSpeedModifier); // 开始计时
            }
        }
    }

    private void Fire()
    {
        audio.PlayOneShot(ShotSound);
        GameObject bullet = Instantiate(bulletPrefab, muzzlePos.position, Quaternion.identity);
        Bullet bulletScript = bullet.GetComponent<Bullet>();
        bulletScript.SetSpeed(direction, player.stats.bulletSpeed,player.stats.tempBulletSpeed, player.stats.bulletSpeedModifier); // 传递角色弹速，临时弹速，武器弹速和弹速修正系数
    }
}
